package com.haixiaoke.smartLock.youdian;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.common.core.redis.RedisCache;
import com.haixiaoke.common.utils.DateUtils;
import com.haixiaoke.domain.SmartLock;
import com.haixiaoke.service.impl.SmartLockServiceImpl;
import com.haixiaoke.smartLock.base.SmartLockBasicsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 优电智能锁接口
 * xiaolong
 * 2023-06-08
 */
@Service
public class SmartLockYdService implements SmartLockBasicsService {

    @Autowired
    private RedisCache redisCache;
    @Value("${youDian.url}")
    private String youDianUrl;
    //公司名
    @Value("${youDian.companyName}")
    private String youDianCompanyName;
    //服务电话
    @Value("${youDian.serviceTel}")
    private String youDianServiceTel;
    //公司地址
    @Value("${youDian.companyAddress}")
    private String youDianCompanyAddress;
    //负责人姓名
    @Value("${youDian.contactsName}")
    private String youDianContactsName;
    //负责人电话号码
    @Value("${youDian.contactsPhoneNumber}")
    private String youDianContactsPhoneNumber;
    @Value("${youDian.token}")
    private String youDianToken;

    /**
     * 获取优电平台注册公司
     *
     * @return
     */
    public String getToken() {
        String youDianToken = redisCache.getCacheObject("sys_youDianToken");
        if (StringUtils.isEmpty(youDianToken)) {
            try {
                Map<String, String> params = new HashMap<>();
                params.put("companyName", youDianCompanyName);
                params.put("serviceTel", youDianServiceTel);
                params.put("companyAddress", youDianCompanyAddress);
                params.put("contactsName", youDianContactsName);
                params.put("contactsPhoneNumber", youDianContactsPhoneNumber);
                params.put("pushUrl", "");
                //执行POST请求
                String result = HttpRequest.post(youDianUrl + "company")
                        .body(JSONObject.toJSONString(params))
                        .timeout(20000)
                        .execute().body();
                Integer code = (Integer) JSONObject.parseObject(result).get("code");
                if (code == 0) {
                    Object data = JSONObject.parseObject(result).get("data");
                    JSONObject jsonObject = JSONObject.parseObject(data.toString());
                    Object token = jsonObject.get("token");
                    redisCache.setCacheObject("sys_youDianToken", token.toString(), 30, TimeUnit.MINUTES);
                    return token.toString();
                } else {
                    String message = (String) JSONObject.parseObject(result).get("message");
                    return message;
                }
            } catch (Exception e) {
                return "获取失败";
            }
        }
        return youDianToken;
    }

    /**
     * 注册设备
     *
     * @param smartLock 智能锁设备信息
     * @return
     */
    public String insertSmartLock(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei", smartLock.getSn());
        hashMap.put("deviceModel", smartLock.getModelName());
        hashMap.put("buttPlatformType", SmartLock.BUTT_PLATFORM_TYPE_TELECOM);
        String result = HttpRequest.post(youDianUrl + "commercial/device")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 获取智能锁设备信息
     *
     * @param smartLock 智能锁设备信息
     * @return
     */
    @Override
    public String getSmartLock(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei", smartLock.getSn());
        String result = HttpRequest.get(youDianUrl + "commercial/device")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .form(hashMap)
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    @Override
    public String getSmartLockDetails(SmartLock smartLock) {
        return null;
    }

    @Override
    public String getLockPassword(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        //添加指纹数据
        hashMap.put("imei", smartLock.getSn());
        hashMap.put("pageNum", 1);
        hashMap.put("pageSize", 100);
        hashMap.put("passwordType", SmartLock.PASSWORD_TYPE_NUMBER);
        String result = HttpRequest.get(youDianUrl + "commercial/device/password/list")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .form(hashMap)
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    @Override
    public String getBluetooth(SmartLock smartLock) {
        return null;
    }

    @Override
    public String deleteBle(SmartLock smartLock) {
        return null;
    }

    @Override
    public String addBluetooth(SmartLock smartLock) {
        return null;
    }

    @Override
    public String addFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    public String sendFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    public String deleteFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    public String offlinePassword(SmartLock smartLock) {
        return null;
    }

    @Override
    public String remoteUnlock(SmartLock smartLock) {
        return null;
    }


    /**
     * 新增智能锁密码授权信息
     *
     * @param smartLock 智能锁密码授权信息
     * @return
     */
    @Override
    public String addPassword(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei", smartLock.getSn());
        hashMap.put("password", smartLock.getPassword());
        hashMap.put("passwordType", SmartLock.PASSWORD_TYPE_NUMBER);
        hashMap.put("permanentFlag", SmartLock.PERMANENT_FLAG_NO);
        hashMap.put("passwordAuth", SmartLock.PASSWORD_AUTH_TYPE_GENERAL);
        hashMap.put("startTime", smartLock.getStartTime());
        hashMap.put("endTime", smartLock.getEndTime());
        String result = HttpRequest.post(youDianUrl + "commercial/device/password")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }


    /**
     * 删除智能锁密码授权信息
     *
     * @return
     */
    @Override
    public String deletePwd(SmartLock smartLock) {
        String result = HttpRequest.delete(youDianUrl + "commercial/device/password?id=" + smartLock.getReturnPwdId())
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }


    /**
     * 新增智能锁门卡授权信息
     *
     * @param smartLock 智能锁门卡授权信息
     * @return
     */
    @Override
    public String addCard(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei", smartLock.getSn());
        hashMap.put("password", smartLock.getCardNumber());
        hashMap.put("passwordType", SmartLock.PASSWORD_TYPE_CARD);
        hashMap.put("permanentFlag", SmartLock.PERMANENT_FLAG_NO);
        hashMap.put("passwordAuth", SmartLock.PASSWORD_AUTH_TYPE_GENERAL);
        hashMap.put("startTime", smartLock.getStartTime());
        hashMap.put("endTime", smartLock.getEndTime());
        hashMap.put("icCardModel", smartLock.getCardType());
        String result = HttpRequest.post(youDianUrl + "commercial/device/password")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }


    /**
     * 删除智能锁门卡授权信息
     *
     * @return
     */
    @Override
    public String deleteCard(SmartLock smartLock) {
        String result = HttpRequest.delete(youDianUrl + "commercial/device/password?id=" + smartLock.getReturnCardId())
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    @Override
    public String getUnlockKey(SmartLock smartLock) {
        return null;
    }

    /**
     * 新增智能锁授权人脸信息
     *
     * @param smartLock 智能锁设备信息
     * @return 结果
     */
    @Override
    public String addFaceImage(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("imei", smartLock.getSn());
        hashMap.put("faceImage", smartLock.getFaceImage());
        hashMap.put("passwordType", SmartLock.PASSWORD_TYPE_FACE);
        hashMap.put("permanentFlag", smartLock.getPasswordType());
        hashMap.put("passwordAuth", SmartLock.PASSWORD_AUTH_TYPE_GENERAL);
        hashMap.put("startTime", smartLock.getStartTime());
        hashMap.put("endTime", smartLock.getEndTime());
        String result = HttpRequest.post(youDianUrl + "commercial/device/password")
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 删除人脸授权信息
     *
     * @param smartLock 智能锁设备信息
     * @return
     */
    @Override
    public String deleteFace(SmartLock smartLock) {
        String result = HttpRequest.delete(youDianUrl + "commercial/device/password?id=" + smartLock.getReturnFaceId())
                .header("token", youDianToken)
                .timeout(20000)
                .execute().body();
        return result;
    }

    @Override
    public String getTaskList(SmartLock smartLock) {
        return null;
    }

    /**
     * 删除智能锁所有授权及解绑
     *
     * @param sn
     * @return
     */
    public String deleteAll(String sn) {
        String result = HttpRequest.delete(youDianUrl + "commercial/device?imei=" + sn)
                .header("token", youDianToken)//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }
}
